package com.pkk.spring.cloud.service.gateway.global;

import java.net.InetSocketAddress;
import java.net.URI;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 请求过滤器
 *
 * @author peikunkun
 * @version V1.0
 * @date 2021-01-25 17:48
 **/
@Slf4j
public class HttpRequestGlobalFilter implements GlobalFilter, Ordered {

  /**
   * Process the Web request and (optionally) delegate to the next {@code WebFilter}
   * through the given {@link GatewayFilterChain}.
   *
   * @param exchange the current server exchange
   * @param chain provides a way to delegate to the next filter
   * @return {@code Mono<Void>} to indicate when request processing is complete
   */
  @Override
  public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
    ServerHttpRequest request = exchange.getRequest();
    //得到请求参数
    final InetSocketAddress remoteAddress = request.getRemoteAddress();
    final URI uri = request.getURI();
    final MultiValueMap<String, String> queryParams = request.getQueryParams();
    log.debug("【Gateway】-[请求]-[{}]-[{}]-[{}]", remoteAddress.getAddress(), uri, queryParams);

    //拦截
    //return exchange.getResponse().setComplete();
    //放行请求
    return chain.filter(exchange);
  }

  /**
   * 优先地位
   * <p>
   * 获取此对象的订单值。
   * <p>较高的值被解释为较低的优先级。因此，
   * 值最低的对象具有最高优先级（有点类似于Servlet @ code-start-startup}值）。
   *
   * <p>相同的顺序值将导致*受影响对象的任意排序位置。
   *
   * @返回订单值* @请参阅#HIGHEST_PRECEDENCE * @请参阅#LOWEST_PRECEDENCE
   */
  @Override
  public int getOrder() {
    return Ordered.HIGHEST_PRECEDENCE;
  }
}
